package com.open.capacity.notice.event;

import org.springframework.stereotype.Service;

import com.open.capacity.common.disruptor.AsyncContext;
import com.open.capacity.common.disruptor.annocation.Channel;
import com.open.capacity.common.disruptor.event.BaseEvent;
import com.open.capacity.common.disruptor.listener.EventListener;
import com.open.capacity.notice.constant.Topic;
import com.open.capacity.notice.enums.SendMessageTaskStatus;
import com.open.capacity.notice.processor.CreateTaskProcessorFactory;
import com.open.capacity.notice.provider.MessageError;
import com.open.capacity.redis.repository.RedisLockService;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

/**
 * 三方发送事件监听
 *
 */
@Service
@Channel(Topic.NAME)
@RequiredArgsConstructor
public class SendMessageEventLisener extends EventListener<SendMessageEvent, AsyncContext> {

	private final CreateTaskProcessorFactory createTaskProcessorFactory;

	private final RedisLockService redisLockService;

	@Override
	public boolean accept(BaseEvent event) {
		if (event instanceof SendMessageEvent) {
			return true;
		}
		return false;
	}

	@Override
	@SneakyThrows
	public void onEvent(SendMessageEvent event, AsyncContext eventContext) {
		String taskId = event.getSendMessageTask().getId();
		if (redisLockService.tryLock(taskId)) {
			try {
				createTaskProcessorFactory.getCreateTaskService(event.getSendMessageTask())
						.sendMessage(event.getSendMessageTask());
			} catch (Exception e) {
				event.getSendMessageTask().setStatus(SendMessageTaskStatus.FAILURE);
				event.getSendMessageTask().setFailure(MessageError.COMSUMER_ERROR.getErrorMessage());
				createTaskProcessorFactory.getCreateTaskService(event.getSendMessageTask()).getSendMessageTaskService()
						.updateById(event.getSendMessageTask());
			} finally {
				redisLockService.unlock(taskId);
			}
		}

	}

}
